#!/usr/bin/env python
# encoding: utf-8

import base64
import json
from generate_dbxml import create_db_config
from generate_log4netxml import create_log4net_config
from util import cur_file_dir
from win_service_helper import add_blank_to_facedeteive_server, get_blank_page, get_blank_count_from_server, \
    get_blank_item_from_server, del_blank_by_guid_from_server, clear_blank, get_log_count_from_service, \
    get_logs_from_service
from win_service_manage_helper import start_winservice, query_winservice_started, stop_and_start_winservice

__author__ = '马志'

"""

by: 马志 at: 2016/8/22 14:02
@contact: hautmz@163.com
@file: web_hander.py
"""

from bottle import Bottle, run
import bottle
from bottle import route, install, template, request, response
from bottle_sqlite import SQLitePlugin
import bottle_api_json_formatting

path = cur_file_dir()
db_path = path + '\PluginServiceWebServer.db'
app = Bottle()

app.install(SQLitePlugin(dbfile=db_path))
json_format_plugin = bottle_api_json_formatting.JsonFormatting()
app.install(json_format_plugin)


@app.route("/test")
def test():
    return "success"


@app.route("/path")
def get_exe_path():
    return cur_file_dir()


@app.route("/dbpath")
def get_db_path():
    return db_path


@app.route("/", skip=[json_format_plugin])
def show_index():
    return template(path + '/static/main.html')


@app.route("/loglist.html", skip=[json_format_plugin])
def loglist():
    return template(path + '/static/loglist.html')


@app.route("/index.html", skip=[json_format_plugin])
def index():
    return template(path + '/static/index.html')


@app.route("/winservice.html", skip=[json_format_plugin])
def windservice_html():
    winstatus = query_winservice_started()
    info = "未知"
    if winstatus == "NOTEXIST":
        info = "未安装PluginService"
    elif winstatus == "STOPPED":
        info = "已停止"
    elif winstatus == "RUNNING":
        info = "已启动"
    return template(path + '/static/winservice.html', info=info, status=winstatus)


@app.route("/dbconfig.html", skip=[json_format_plugin])
def dbconfig_html():
    return template(path + '/static/dbconfig.html')


@app.route("/get_pluginservice_state")
def get_pluginservice_state():
    return query_winservice_started()


@app.route("/stop_pluginservice")
def stop_pluginservice():
    stop_and_start_winservice("stop")


@app.route("/start_pluginservice")
def start_pluginservice():
    stop_and_start_winservice("start")


@app.route("/main", skip=[json_format_plugin])
def go_main():
    return template(path + '/static/main.html')


@app.route("/algithm.html", skip=[json_format_plugin])
def algithm(db):
    c = db.execute("SELECT * from ObjectKeyValue").fetchall()
    data = {}
    for item in c:
        data[item[1]] = item[2]
    return template(path + '/static/algithm.html', config=data)


@app.route("/get_algithm_config")
def get_algorithm_config(db):
    c = db.execute("SELECT * from ObjectKeyValue WHERE id<6").fetchall()
    data = {}
    for item in c:
        data[item[1]] = float(item[2])
    return data


@app.route("/del_all_blank", method="GET")
def del_all_blank():
    return clear_blank()


@app.route("/updata_algithm_config", method="POST")
def updata_algithm_config(db):
    request_json = request.json
    if request_json:
        try:
            thread_count = request_json["thread_count"]
            thread_sleep_time = request_json["thread_sleep_time"]
            thresold = request_json["thresold"]
            max_face_count = request_json["max_face_count"]
            db.execute("update ObjectKeyValue SET value=%s WHERE key='thread_count'" % thread_count)
            db.execute("update ObjectKeyValue SET value=%s WHERE key='thread_sleep_time'" % thread_sleep_time)
            db.execute("update ObjectKeyValue SET value=%s WHERE key='thresold'" % thresold)
            db.execute("update ObjectKeyValue SET value=%s WHERE key='max_face_count'" % max_face_count)
            db.commit()
            stop_and_start_winservice("stop")
            stop_and_start_winservice("start")
            return "success"
        except Exception, e:
            return "failed"


@app.route('/camera.html', skip=[json_format_plugin])
def camera(db):
    row = db.execute('SELECT * from Camera').fetchall()
    type_key_value = {"FILE": "文件", "USB": "USB", "HIK": "海康", "DAHUA": "大华"}
    data = []
    for t in row:
        item = []
        item.append(t[0])
        item.append(t[1])
        item.append(t[2])
        item.append(t[3])
        item.append(t[4])
        item.append(t[5])
        item.append(type_key_value.get(t[6]))
        item.append(t[7])
        item.append(t[8])
        data.append(item)
    if row:
        return template(path + '\static\camera.html', cameras=data)
    else:
        return "没有摄像机数据"


@app.route('/cameraEdit.html', skip=[json_format_plugin])
def edit_camera():
    return template(path + '\static\cameraEdit.html')


@app.route('/change_state/<id>')
def change_state(db, id):
    row = db.execute('SELECT vaild FROM Camera WHERE DbId=%s' % (id)).fetchone()
    if row:
        valid = 0
        print int(row[0])
        if int(row[0]) == 0:
            valid = 1
        else:
            valid = 0
        sql = "UPDATE Camera SET vaild=%d WHERE DbId=%s" % (valid, id)
        db.execute(sql)
        db.commit()
        return "ture"
    return "false"


@app.route('/js/<filename>', skip=[json_format_plugin])
def get_js_file(filename):
    return bottle.static_file(filename, path + "\\static\js\\")


@app.route('/update', method='POST')
def update_camera(db):
    camera_json = request.json
    if camera_json:
        try:
            address = camera_json["address"]
            dbid = camera_json["dbid"]
            id = camera_json["id"]
            port = camera_json["port"]
            user_name = camera_json["user_name"]
            pass_word = camera_json["pass_word"]
            type_id = camera_json["type_id"]
            sql = "update Camera SET id='%s',address='%s',port=%s,username='%s',password='%s',typeid='%s' where dbid=%s" % (
                id, address, port, user_name, pass_word, type_id, dbid)
            db.execute(sql)
            db.commit()
            return True
        except Exception, e:
            print e
            return False
    else:
        return False


@app.route("/images/<filename>", skip=[json_format_plugin])
def get_img_file(filename):
    return bottle.static_file(filename, path + "/static/images/")


@app.route("/css/<filename>", skip=[json_format_plugin])
def get_css_file(filename):
    return bottle.static_file(filename, path + "/static/css/")


@app.route("/get_cameras")
def get_cameras(db):
    row = db.execute('SELECT * from Camera WHERE vaild=1').fetchall()
    data = []
    if row:
        for c in row:
            data.append(
                {"Id": c[1], "Address": c[2], "Port": int(c[3]), "UserName": c[4], "PassWord": c[5],
                 "TypeId": c[6]})
        return data
    return None


@app.route("/get_camera/<dbid>")
def get_camera(db, dbid):
    c = db.execute("SELECT * from Camera WHERE dbid=%s" % dbid).fetchone()
    if c:
        return {"Id": c[1], "Address": c[2], "Port": int(c[3]), "UserName": c[4], "PassWord": c[5], "TypeId": c[6],
                "Vaild": c[7]}
    return None


@app.route("/upstate_camera_state/<dbid>/<vaild>")
def update_camera_state(db, dbid, vaild):
    try:
        sql = "update camera SET vaild=%s WHERE dbid=%s" % (vaild, dbid)
        db.execute(sql)
        db.commit()
        return True
    except Exception, e:
        return False


@app.route("/add_blank", method='POST')
def add_balank():
    try:
        request_json_str = request.json
        if request_json_str:
            request_json = json.loads(request_json_str)
            img_base64 = request_json['img']
            return add_blank_to_facedeteive_server(request_json)
    except Exception, e:
        return None


@app.route("/get_log", method='GET')
def get_log():
    pass


# 添加黑名单
@app.route("/RegisterPic.html", skip=[json_format_plugin])
def register_pic():
    response = get_blank_page({"PageIndex": 1, "PageSize": 10, "CurrentPage": 1})
    return template(path + '/static/RegisterPic.html')


@app.route("/Get_Page_Blank", method="POST")
def Get_Page_Blank():
    request_data = request.json
    if request_data:
        return get_blank_page({"PageIndex": request_data.get("PageIndex"), "PageSize": request_data.get("PageSize")})


@app.route("/RegisterPicEdit.html", skip=[json_format_plugin])
def register_pic_edit():
    return template(path + '/static/RegisterPicEdit.html')


@app.route('/upload', method='POST')
def do_upload():
    blank_name = request.POST.get('blank_name')
    blank_id = request.POST.get('blank_id')
    if blank_name and blank_id:
        data = request.POST.get('userfile').file.read();
        if data:
            base64_str = base64.b64encode(data)
            if base64_str:
                response = add_blank_to_facedeteive_server(
                    {"ImageBase64Str": base64_str, "Id": blank_id, "Name": blank_name})
                return response
    return None


@app.route('/get_blank_image/<guid>', method='GET', skip=[json_format_plugin])
def get_blank_image(guid):
    data = get_blank_item_from_server(guid)
    if data:
        try:
            response.set_header('Content-type', 'image/jpeg')
            bas64_image = data["MessageBody"].get("ImageBase64")
            return base64.b64decode(bas64_image)
        except Exception, e:
            return None


@app.route('/get_blank_count', method='GET')
def get_blank_count():
    return get_blank_count_from_server()


@app.route('/del_blank_by_guid/<guid>', method='GET')
def del_blank_by_guid(guid):
    return del_blank_by_guid_from_server(guid)


@app.route('/get_db_sqlmap', method='GET', skip=[json_format_plugin])
def get_db_sqlmap(db):
    # db_file=path+"/static/dbconfigs/sqlite.xml"
    # db_file=path+"/static/dbconfigs/mysql.xml"
    db_type = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_type'").fetchone()
    db_username = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_username'").fetchone()
    db_name = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_name'").fetchone()
    db_psd = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_psd'").fetchone()
    db_host = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_host'").fetchone()
    db_port = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_port'").fetchone()
    ibatis_map_file = create_db_config(db_type[0], db_name[0], db_host[0], db_port[0], db_username[0], db_psd[0])
    return ibatis_map_file.toprettyxml(indent = "\t", newl = "\n", encoding = "utf-8")
    # db_file = path + "/static/dbconfigs/sqlserver.xml"
    # with open(db_file, 'rb') as r:
    #     return r.read()


@app.route("/get_dbconfig", method="GET")
def get_dbconfig(db):
    try:
        db_type = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_type'").fetchone()
        db_username = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_username'").fetchone()
        db_name = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_name'").fetchone()
        db_psd = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_psd'").fetchone()
        db_host = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_host'").fetchone()
        db_port = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_port'").fetchone()
        return {"db_type": db_type[0], "db_username": db_username[0], "db_name": db_name[0], "db_psd": db_psd[0],
                "db_host": db_host[0], "db_port": db_port[0]}
    except Exception, e:
        return {}


@app.route("/save_dbconfig", method="POST")
def save_dbconfig(db):
    try:
        request_data = request.json
        db_type = request_data["db_type"]
        db_username = request_data["db_username"]
        db_name = request_data["db_name"]
        db_psd = request_data["db_psd"]
        db_host = request_data["db_host"]
        db_port = request_data["db_port"]
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_type'" % db_type)
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_username'" % db_username)
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_psd'" % db_psd)
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_host'" % db_host)
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_port'" % db_port)
        db.execute("update ObjectKeyValue SET value='%s' WHERE key='db_name'" % db_name)
        db.commit()
        return True
    except Exception, e:
        return False


@app.route("/test_db", method="GET")
def test_db(db):
    pass


@app.route("/log4net", method="GET", skip=[json_format_plugin])
def log4net(db):
    db_type = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_type'").fetchone()
    db_username = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_username'").fetchone()
    db_name = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_name'").fetchone()
    db_psd = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_psd'").fetchone()
    db_host = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_host'").fetchone()
    db_port = db.execute("select VALUE FROM ObjectKeyValue WHERE KEY ='db_port'").fetchone()
    log4net_config=create_log4net_config(db_type[0],db_name[0],db_host[0],db_port[0],db_username[0],db_psd[0])
    # f = open("book_store.xml", "w")
    # f.write(log4net_config.toprettyxml(indent = "\t", encoding = "utf-8"))
    # f.close()
    return log4net_config.toprettyxml(indent = "")
    # if int(db_type[0])==0:
    #     db_file = path + "/static/log4net/sqlite_log.xml"
    # elif int(db_type[0])==1:
    #     db_file = path + "/static/log4net/mysql_log.xml"
    # elif int(db_type[0])==2:
    #     db_file = path + "/static/log4net/sqlserver_log.xml"
    # # db_file = path + "/static/log4net/sqlite_log.xml"
    # with open(db_file, 'rb') as r:
    #     return r.read()


@app.route("/get_log_count", method="GET")
def get_log_count():
    """
    获取日志总数
    by: 马志 at: ${DATE} ${TIME}
    """
    return get_log_count_from_service()


@app.route("/get_logs", method="POST")
def get_logs():
    """

    by: 马志 at: ${DATE} ${TIME}
    """
    request_data = request.json
    if request_data:
        return get_logs_from_service(
            {"PageIndex": request_data.get("PageIndex"), "PageSize": request_data.get("PageSize")})


# @app.route('/download/')
# def index(file_name):
#     grid_fs_file = grid_fs.find_one({'filename': file_name})
#     response = make_response(grid_fs_file.read())
#     response.headers['Content-Type'] = 'application/octet-stream'
#     response.headers["Content-Disposition"] = "attachment; filename={}".format(file_name)
#     return response

run(app, host='localhost', port=8110, debug=True, reloader=True)
